package com.weipeep.sys.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.weipeep.common.annotation.Log;
import com.weipeep.common.base.BaseController;
import com.weipeep.common.domain.Tree;
import com.weipeep.common.mail.EmailService;
import com.weipeep.common.type.EnumErrorCode;
import com.weipeep.common.utils.MD5Utils;
import com.weipeep.common.utils.Result;
import com.weipeep.common.utils.ShiroUtils;
import com.weipeep.sys.config.Constant;
import com.weipeep.sys.domain.*;
import com.weipeep.sys.service.*;
import com.weipeep.sys.vo.CompanyResponse;
import com.weipeep.sys.vo.ProductResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * <pre>
 * </pre>
 * <small> 2018年3月23日 | wangyun</small>
 */
@Controller
public class LoginController extends BaseController {

    @Autowired
    MenuService menuService;
    @Autowired
    DemandService demandService;
    @Autowired
    WebUserService webUserService;
    @Autowired
    ProductService productService;
    @Autowired
    NewsService newsService;
    @Resource
    private EmailService emailService;
    @GetMapping({"/", ""})
    String welcome(Model model) {
        return "redirect:/front/index";
    }

    @GetMapping("/login")
    String login() {
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    Result<String> ajaxLogin(String username, String password,Integer roleType) {
        password = MD5Utils.encrypt(username, password);
        if (roleType==null){
            roleType=1;
        }
        username = username+"#&#"+roleType;
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            if (roleType==1){
                return Result.ok().setData("member");
            }else {
                return Result.ok().setData("admin");
            }

        } catch (AuthenticationException e) {
            return Result.build(EnumErrorCode.userLoginFail.getCode(), e.getMessage());
        }
    }

    @GetMapping("/front/register")
    String register(Model model) {
        UserBase webUserDO = getUser();
        if(webUserDO!=null){
            model.addAttribute("user",webUserDO);
            model.addAttribute("isLogin",true);
        }else {
            model.addAttribute("isLogin",false);
        }
        return "register";
    }

    @PostMapping("/front/checkAccount")
    @ResponseBody
    Result<String> checkAccount(String userAccount) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("user_account", userAccount);
        List<WebUserDO> webUserDOList = webUserService.selectByMap(map);
        if (webUserDOList != null && webUserDOList.size() > 0) {
            return Result.fail();
        } else {
            return Result.ok();
        }
    }

    @PostMapping("/front/register")
    @ResponseBody
    Result<String> register(WebUserDO webUserDO) {
        WebUserDO dd = new WebUserDO();
        dd.setCompany(webUserDO.getCompany());
        Wrapper<WebUserDO> wrapper = new EntityWrapper<>(dd);
        if(webUserService.selectList(wrapper).size()>0){
            return Result.fail().setMsg("公司已经注册");
        }
        String password = MD5Utils.encrypt(webUserDO.getUserAccount(), webUserDO.getPassword());
        webUserDO.setPassword(password);
        webUserDO.setRegisterTime(Calendar.getInstance().getTime());
        webUserDO.setStatus(Constant.notExpire);
        webUserDO.setMemberLevel(Constant.memberLevelCommon);
        Boolean b = webUserService.insert(webUserDO);
        String company=webUserDO.getCompany();
        String userAccount = webUserDO.getUserAccount();
        String member=webUserDO.getMemberType()==1?"买家":webUserDO.getMemberType()==2?"卖家":"买家和卖家都是";
        NewsDO newsDO = newsService.selectById(25L);
        String result = newsDO.getContent().replace("#{company}",company);
        result = result.replace("#{userAccount}",userAccount);
        result = result.replace("#{memberType}",member);
        final String emailContent = result;
        new Thread(){
            @Override
            public void run() {
                emailService.sendHtmlMail(webUserDO.getEmail(),"一号轴承网注册成功通知",emailContent);
            }
        }.start();
        if (b) {
            return Result.ok();
        } else {
            return Result.fail().setMsg("注册失败");
        }
    }

    public static void main(String[] args) {
        System.out.println(MD5Utils.encrypt("admin", "admin"));
    }

    @GetMapping("/logout")
    String logout() {
        ShiroUtils.logout();
        return "redirect:/front/index";
    }

    @GetMapping("/main")
    String main() {
        return "main";
    }

    @GetMapping("/front/index")
    String main1(Model model) {
        Wrapper<DemandDO> wrapperDemandDO = new EntityWrapper<DemandDO>();
        wrapperDemandDO.orderBy("id desc");
        List<DemandDO> commonList = demandService.selectList(wrapperDemandDO);
        List<ProductResponse> productResponseList = productService.fetchLatestProducts(null,1,20,0);
        List<ProductResponse> hotsellList = productService.fetchLatestProducts(null,1,20,1);
        Wrapper<WebUserDO> wrapper = new EntityWrapper<WebUserDO>();
        wrapper.orderBy("id desc");
        List<WebUserDO> webUserDOList = webUserService.selectList(wrapper);
        Set<String> companys = Sets.newHashSet();
        List<CompanyResponse> latestCompanyList = Lists.newArrayList();
        webUserDOList.forEach(webUserDO -> {
            if (webUserDO.getCompany()!=null && !companys.contains(webUserDO.getCompany())){
                CompanyResponse companyResponse = new CompanyResponse();
                companyResponse.setCompanyName(webUserDO.getCompany());
                companyResponse.setWebSite("/front/"+webUserDO.getUserAccount());
                latestCompanyList.add(companyResponse);
                companys.add(webUserDO.getCompany());
            }
        });
        Map<String,Object> map = Maps.newHashMap();
        map.put("recommend_sign",1);
        List<WebUserDO> reccowebUserDOList = webUserService.selectByMap(map);
        Set<String> reccocompanys = Sets.newHashSet();
        List<CompanyResponse> recommendCompanyList = Lists.newArrayList();
        reccowebUserDOList.forEach(webUserDO -> {
            if (webUserDO.getCompany()!=null && !reccocompanys.contains(webUserDO.getCompany())){
                CompanyResponse companyResponse = new CompanyResponse();
                companyResponse.setCompanyName(webUserDO.getCompany());
                companyResponse.setWebSite("/front/"+webUserDO.getUserAccount());
                recommendCompanyList.add(companyResponse);
                reccocompanys.add(webUserDO.getCompany());
            }
        });
        if(commonList.size()>20){
            model.addAttribute("commonList",commonList.subList(0,20));
        }else {
            model.addAttribute("commonList",commonList);
        }
        model.addAttribute("productList",productResponseList);
        model.addAttribute("hotsellList",hotsellList);
        if(latestCompanyList.size()>20){
            model.addAttribute("latestCompanyList", latestCompanyList.subList(0,20));
        }else {
            model.addAttribute("latestCompanyList", latestCompanyList);
        }
        if(recommendCompanyList.size()>20){
            model.addAttribute("recommendCompanyList", recommendCompanyList.subList(0,20));
        }else {
            model.addAttribute("recommendCompanyList", recommendCompanyList);
        }
        UserBase webUserDO = getUser();
        if(webUserDO!=null){
            model.addAttribute("user",webUserDO);
            model.addAttribute("isLogin",true);
        }else {
            model.addAttribute("isLogin",false);
        }
        return "index";
    }
    @GetMapping("/front/{userAccount}")
    String main(@PathVariable("userAccount") String userAccount, Model model) {
        WebUserDO webUserDOSearch =new WebUserDO();
        webUserDOSearch.setUserAccount(userAccount);
        Wrapper<WebUserDO> wrapperSearch = new EntityWrapper<WebUserDO>(webUserDOSearch);
        WebUserDO owner = webUserService.selectOne(wrapperSearch);
        if (owner==null){
            return "redirect:/front/index";
        }
        model.addAttribute("memberType",owner.getMemberType());
        model.addAttribute("owner",owner);
        DemandDO demandDO = new DemandDO();
        demandDO.setUserId(owner.getId());
        Wrapper<DemandDO> wrapperDemandDO = new EntityWrapper<DemandDO>(demandDO);
        wrapperDemandDO.orderBy("id desc");
        List<DemandDO> commonList = demandService.selectList(wrapperDemandDO);
        List<ProductResponse> productResponseList = productService.fetchOwnLatestProducts(owner.getId(),1,20,0);
        List<ProductResponse> hotsellList = productService.fetchOwnLatestProducts(owner.getId(),1,20,1);
        if(commonList.size()>20){
            model.addAttribute("commonList",commonList.subList(0,20));
        }else {
            model.addAttribute("commonList",commonList);
        }
        model.addAttribute("productList",productResponseList);
        model.addAttribute("hotsellList",hotsellList);
        UserBase webUserDO = getUser();
        if(webUserDO!=null){
            model.addAttribute("user",webUserDO);
            model.addAttribute("isLogin",true);
        }else {
            model.addAttribute("isLogin",false);
        }
        return "personalIndex";
    }
    @GetMapping("/403")
    String error403() {
        return "403";
    }

}
